package com.basil.gym.controller;

import com.basil.gym.constants.RedisConstants;
import com.basil.gym.util.AliOSSUtil;
import com.basil.gym.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

@Controller
public class UploadController {
    @Autowired
    private RedisTemplate redisTemplate;

    @RequestMapping(value = "/upload", method = {RequestMethod.POST})
    @ResponseBody
    public Result upload(MultipartFile file) {
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String fileName = file.getOriginalFilename();
        String extension = fileName.substring(fileName.lastIndexOf("."));
        String newFileName = uuid + extension;

        // 将文件上传到阿里云OSS
        String url = "";
        try {
            url = AliOSSUtil.uploadFile(newFileName, file.getInputStream());
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("上传失败");
        }
        //将所有上传的图片放到redis的set集合中
        redisTemplate.opsForSet().add(RedisConstants.UPLOAD_IMAGE, url);
        return Result.ok("上传成功", url);
    }
}
